import KoaRouter from 'koa-router';
import ProjectController from '../controllers/project.js';
import RES_MSG from '../shared/response-message.js';

const projectRouter = new KoaRouter({
    prefix: '/api/project'
});

projectRouter.get('/', async function (ctx) {
    const data = await new ProjectController().projects();
    ctx.body = {
        data,
        message: RES_MSG.OK
    };
});

projectRouter.get('/:id', async function (ctx) {
  const id = +ctx.params.id;
  if (!id) {
    ctx.statusCode = 400;
    ctx.body = {
      message: RES_MSG.PARAMS_INVALID
    };
    return;
  }
  const data = await new ProjectController().project(id);
  ctx.body = {
      data,
      message: RES_MSG.OK
  };
});

projectRouter.post('/', async function(ctx) {
    const payload = ctx.request.body;
    const id = await new ProjectController().createProject(payload);
    ctx.body = {
        data: id,
        message: RES_MSG.OK
    };
});

projectRouter.put('/:id', async function(ctx) {
    const id = +ctx.params.id;
    const payload = ctx.request.body;

    if (!id) {
      ctx.statusCode = 400;
      ctx.body = {
        message: RES_MSG.PARAMS_INVALID
      };
      return
    }

    await new ProjectController().updateProject(id, payload);
    ctx.body = {
        message: RES_MSG.OK
    }
});

projectRouter.delete('/:id', async function(ctx) {
    const id = +ctx.params.id;
    if (!id) {
      ctx.statusCode = 400;
      ctx.body = {
          message: RES_MSG.PARAMS_INVALID
      };
      return;
    }
    await new ProjectController().deleteProject(id);
    ctx.body = {
        message: RES_MSG.OK
    }
});


export default projectRouter
